// pages/document/submit.js

const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    id: 0,
    detail: {},
    taskTitle: "",
    articleTitle: "",
    taskId: 0,
    topicId: 0,
    latitude: 0,
    longitude: 0,
    position: "",
    videoSrc: "",
    fileUrl: "",
    loaddinghidden: true,
    formats: {},
    readOnly: false,
    keyboardHeight: 0,
    isIOS: false,
    showLoading: false,
    loadingText: '加载中...',
    // 审核期临时关闭定位功能
    enableLocation: false,
    // 采集功能相关数据
    isCatchViewShow: true,
    articleUrl: "",
    articleUrlNew: "",
    catchApiUrl: "https://laigao.longsunhd.com/api/show/docatch" // 使用正确的采集API地址
  },

  // 顶格排版：移除段落首行缩进与前导空格（&nbsp;/全角空格）
  formatAlignLeft: function () {
    var that = this;
    if (!that.editorCtx) {
      wx.showToast({ title: '编辑器未就绪', icon: 'none' });
      return;
    }
    that.editorCtx.getContents({
      success: (res) => {
        var html = res.html || '';
        if (!html || html === '<p><br></p>') { wx.showToast({ title: '内容为空', icon: 'none' }); return; }
        // 去除样式中的 text-indent
        html = html.replace(/text-indent\s*:\s*[^;"']+;?/gi, '');
        // 移除 <p style=""> 中可能留下的多余分号与空 style
        html = html.replace(/style="\s*;\s*"/gi, '');
        html = html.replace(/style="\s*"/gi, '');
        // 去除段落起始处的 &nbsp; 与全角空格（\u3000）
        html = html.replace(/(<p[^>]*>)(?:\s*(?:&nbsp;|\u3000))+?/gi, '$1');
        that.editorCtx.setContents({
          html: html,
          success: () => wx.showToast({ title: '已顶格', icon: 'success' }),
          fail: () => wx.showToast({ title: '排版失败', icon: 'none' })
        });
      },
      fail: () => wx.showToast({ title: '读取内容失败', icon: 'none' })
    });
  },

  // 空格排版：为每个段落添加 2em 首行缩进
  formatIndentSpace: function () {
    var that = this;
    if (!that.editorCtx) {
      wx.showToast({ title: '编辑器未就绪', icon: 'none' });
      return;
    }
    that.editorCtx.getContents({
      success: (res) => {
        var html = res.html || '';
        if (!html || html === '<p><br></p>') { wx.showToast({ title: '内容为空', icon: 'none' }); return; }
        // 先移除已有的 text-indent，避免叠加
        html = html.replace(/text-indent\s*:\s*[^;"']+;?/gi, '');
        // 在 <p> 上追加 text-indent:2em;
        html = html.replace(/<p(.*?)>/gi, function (m, g1) {
          // 若已有 style，则拼接；否则新增 style
          if (/style\s*=\s*"[^"]*"/i.test(m)) {
            return m.replace(/style\s*=\s*"([^"]*)"/i, function (_, s) {
              var ns = (s || '').trim();
              if (ns && !/;$/ .test(ns)) ns += ';';
              return 'style="' + ns + 'text-indent:2em;"';
            });
          } else {
            return '<p style="text-indent:2em;"' + g1 + '>';
          }
        });
        that.editorCtx.setContents({
          html: html,
          success: () => wx.showToast({ title: '已缩进', icon: 'success' }),
          fail: () => wx.showToast({ title: '排版失败', icon: 'none' })
        });
      },
      fail: () => wx.showToast({ title: '读取内容失败', icon: 'none' })
    });
  },
  // 调用AI接口对当前文章标题和内容进行改写
  rewriteFromAI: function () {
    var that = this;
    if (!that.editorCtx) {
      wx.showModal({ title: '提示', content: '编辑器未就绪' });
      return;
    }
    that.editorCtx.getContents({
      success: (res) => {
        var html = res.html || '';
        var title = that.data.articleTitle || '';
        if ((!html || html === '<p><br></p>') && !title) {
          wx.showModal({ title: '提示', content: '请先填写标题或内容后再改写' });
          return;
        }

        that.showLoading('改写中...');
        var parameter = {
          title: title,
          content: html
        };
        http.ApiPost(apiUrl.UrlAiRewrite, parameter, function (resp) {
          that.cancelLoading();
          if (!resp) {
            wx.showModal({ title: '改写失败', content: '网络异常，请稍后再试' });
            return;
          }
          if (resp.code == 1 && resp.data) {
            var newTitle = resp.data.title || title;
            var newHtml = resp.data.content || html;
            that.setData({ articleTitle: newTitle });
            if (newHtml) {
              that.editorCtx.setContents({
                html: newHtml,
                success: () => { wx.showToast({ title: '改写完成', icon: 'success' }); },
                fail: () => { wx.showToast({ title: '内容设置失败', icon: 'none' }); }
              });
            } else {
              wx.showToast({ title: '改写完成', icon: 'success' });
            }
          } else {
            wx.showModal({ title: '改写失败', content: resp.msg || 'AI改写失败，请稍后再试' });
          }
        });
      },
      fail: () => {
        wx.showModal({ title: '提示', content: '无法读取当前内容' });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this
    var id = options.id;
    if (id) {
      that.setData({
        id: id
      })
      wx.setNavigationBarTitle({
        title: '编辑稿件',
      })
      that.loadData();
    }
    var taskId = options.task_id;
    if (taskId) {
      that.setData({
        taskId: taskId
      })
    }
    var topicId = options.topic_id;
    if (topicId) {
      that.setData({
        topicId: topicId
      })
    }
    var taskTitle = options.task_title;
    if (taskTitle) {
      that.setData({
        taskTitle: taskTitle
      })
    }

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    /**
        * 获取系统信息
        */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })

    // 审核期临时关闭定位：不获取定位
    if (this.data.enableLocation) {
      this.safeGetLocation();
    }
  },
  // 运行时检查定位接口可用性与授权
  checkLocationAvailability: function (needChoose, cb) {
    const canGet = !!wx.canIUse && wx.canIUse('getLocation');
    const canChoose = !!wx.canIUse && wx.canIUse('chooseLocation');
    if (!canGet || (needChoose && !canChoose)) {
      wx.showModal({
        title: '提示',
        content: '当前版本未开通定位/选点能力，请稍后重试或跳过位置填写',
        showCancel: false
      });
      typeof cb === 'function' && cb(false, { reason: 'api_unavailable' });
      return;
    }
    wx.getSetting({
      success: (res) => {
        const auth = res.authSetting && res.authSetting['scope.userLocation'];
        if (auth === false) {
          wx.showModal({
            title: '提示',
            content: '未授权位置信息，您可在设置中开启，或跳过位置填写',
            showCancel: false
          });
          cb && cb(false, { reason: 'denied' });
        } else {
          cb && cb(true);
        }
      },
      fail: () => {
        cb && cb(false, { reason: 'get_setting_fail' });
      }
    });
  },
  // 安全封装：获取定位
  safeGetLocation: function () {
    const that = this;
    this.checkLocationAvailability(false, function (ok) {
      if (!ok) return;
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          var latitude = res.latitude
          var longitude = res.longitude
          wx.setStorageSync("latitude", latitude);
          wx.setStorageSync("longitude", longitude);
          that.setData({
            latitude: latitude,
            longitude: longitude
          });
        },
        fail: function(err) {
          console.log("getLocation fail:", err);
        }
      })
    });
  },
  chooseLocation: function() {
    var that = this;
    if (!this.data.enableLocation) {
      wx.showToast({ title: '本版本暂不提供位置功能', icon: 'none' });
      return;
    }
    var latitude = wx.getStorageSync("latitude");
    var longitude = wx.getStorageSync("longitude");
    this.checkLocationAvailability(true, function (ok) {
      if (!ok) return;
      wx.chooseLocation({
        latitude: latitude,
        longitude: longitude,
        success(res) {
          console.log(res);
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            position: res.address,
          });
        },
        fail(err) {
          console.log('chooseLocation fail:', err);
        }
      });
    });
  },
  loadData: function() {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.id;

    http.ApiGet(apiUrl.UrlDocumentDetail, parameter, function(res) {
      if (res.code == 1) {
        that.setData({
          loaddinghidden: true,
          articleTitle: res.data.title,
          detail: res.data,
          videoSrc: res.data.videos,
        });

      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  formSubmit: function(e) {

    var that = this;

    var formData = e.detail.value;

    if (formData.title == "") {
      wx.showModal({
        title: '请填写标题',
      });
      return;
    }
    formData["permission"] = "1";

    var taskId = that.data.taskId;
    if (taskId > 0) {
      formData["task_id"] = taskId;
    }
    var topicId = that.data.topicId;
    if (topicId > 0) {
      formData["topic_id"] = topicId;
    }

    var videoSrc = that.data.videoSrc;
    if (videoSrc.length > 0) {
      formData["videos"] = videoSrc;
    }

    formData["position"] = that.data.position;

    var longitude = that.data.longitude;
    if (longitude > 0) {
      formData["longitude"] = longitude;
    }
    var latitude = that.data.latitude;
    if (latitude > 0) {
      formData["latitude"] = latitude;
    }

    that.editorCtx.getContents({
      success: (res) => {
        console.log(res);
        if (res.text.length > 0 && res.html !="<p><br></p>") {

          var content = res.html;

          var fileUrl = that.data.fileUrl;
          if (fileUrl.length>0){
            content += "<p><a href='" + fileUrl + "'>附件：" + fileUrl + "</a></p>";
          }
          formData["content"] = content;
          that.submitPost(formData);
        } else {
          wx.showModal({
            title: '请填写内容',
          });
          return;
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提交失败',
        });
        console.log(err);
      }
    });
  },
  submitPost(formData) {
    var that = this;

    console.log(formData);
    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    var url = apiUrl.UrlDocumentAdd;
    if (that.data.id > 0) {
      url = apiUrl.UrlDocumentEdit;
      formData["id"] = that.data.id;
    }

    http.ApiPost(url, formData, function(res) {
      if (res.code == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context;
      var detail = that.data.detail;
      if (detail.content) {
        that.editorCtx.setContents({
          html: detail.content,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  textIndent() {
    this.editorCtx.format('textIndent', '2em');
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 9,
      success: function(res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j])
        }
      }
    })
  },
  uploadImage: function(path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUploadImg,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          // console.log(result);
          if (result.code == 1) {
            wx.hideToast();
            that.editorCtx.insertImage({
              src: result.data.url,
              width: '100%',
              success: function() {
                console.log('insert image success');
                that.doRelate(apiUrl.UrlImageRelate, result.data.url);
              }
            })
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  chooseVideo: function() {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        console.log(res)
        that.uploadVideo(res.tempFilePath);
      }
    })
  },
  delVideo: function() {
    var that = this
    wx.showModal({
      title: '确定删除？',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            videoSrc: ''
          })
        }
      }
    })
  },
  uploadVideo: function(path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUploadVideo,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          // console.log(res);
          that.cancelLoading();
          var result = JSON.parse(res.data)
          if (result.code == 1) {
            that.setData({
              videoSrc: result.data.url,
            });
            that.doRelate(apiUrl.UrlVideoRelate, result.data.url);
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log('err');
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  doRelate: function(apiUrl, theUrl) {
    var formData = {};
    formData["url"] = theUrl;

    console.log("doRelate");
    console.log(apiUrl);
    console.log(theUrl);

    var taskId = this.data.taskId;
    if (taskId > 0) {
      formData["task_id"] = taskId;
    }
    var topicId = this.data.topicId;
    if (topicId > 0) {
      formData["topic_id"] = topicId;
    }
    // if (taskId > 0 || topicId > 0) {
      http.ApiPost(apiUrl, formData, function(res) {
        if (res.code == 1) {
          console.log(res.msg);
        } else {
          console.log(res.msg);
        }
      });
    // }
  },
  showLoading: function(text) {
    this.setData({
      showLoading: true,
      loadingText: text || '加载中...'
    })
  },
  cancelLoading: function() {
    this.setData({
      showLoading: false
    })
  },
  fileBtnTap: function () {
    var that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        const tempFilePaths = res.tempFiles;
        console.log(tempFilePaths[0].path);
        that.uploadFile(tempFilePaths[0].path);
      }
    })
  },
  uploadFile: function (path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUpload,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function (res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          console.log(result);
          if (result.code == 1) {
            wx.hideToast();

            var fileUrl = result.data.url;

            that.doRelate(apiUrl.UrlFileRelate, fileUrl);

            that.setData({
              fileUrl: fileUrl
            });

            // that.editorCtx.insertText({
            //   text: fileStr
            // })

            // that.editorCtx.getContents({
            //   success: (getRes) => {
            //     that.editorCtx.setContents({
            //       html: getRes.html + fileStr,
            //       success: (setRes) => {
            //         console.log(setRes);
            //       },
            //     });
            //   }
            // });
           
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function (err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  // 添加采集功能相关方法
  catchViewShow: function () {
    this.setData({
      isCatchViewShow: true
    })
  },

  // 从一段文本中提取“最像且最完整”的 http/https 链接（逐字符扩展，跳过各种空白；严格模式不改写尾部字符）
  extractBestUrl: function (text) {
    if (!text || typeof text !== 'string') return '';
    const candidates = [];
    const httpRegex = /https?:\/\//ig;
    let match;
    while ((match = httpRegex.exec(text)) !== null) {
      let i = match.index;
      let j = i;
      const isUrlChar = (ch) => /[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]/.test(ch);
      const isWhitespaceLike = (ch) => /\s/.test(ch) || /[\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF\u2060\u00AD]/.test(ch);
      let buf = '';
      while (j < text.length) {
        const ch = text[j];
        if (isUrlChar(ch)) {
          buf += ch;
          j++;
        } else if (isWhitespaceLike(ch)) {
          j++;
        } else {
          break;
        }
      }
      if (buf.toLowerCase().startsWith('http')) {
        const hostMatch = buf.match(/^https?:\/\/([^\/\s<>"]+)/i);
        if (hostMatch && hostMatch[1].indexOf('.') !== -1) {
          candidates.push(buf);
        }
      }
      if (httpRegex.lastIndex === match.index) {
        httpRegex.lastIndex++;
      }
    }
    if (candidates.length === 0) return '';
    candidates.sort((a, b) => {
      if (b.length !== a.length) return b.length - a.length;
      const score = (s) => ((s.split('/').length - 3) + (s.includes('?') ? 1 : 0) + (s.includes('#') ? 1 : 0));
      return score(b) - score(a);
    });
    return candidates[0];
  },

  scanCodeTap: function () {
    var that = this;
    wx.scanCode({
      success: (res) => {
        console.log(res);
        if (res.scanType == "CODE_128") {
          wx.showModal({
            title: '提示',
            content: '链接格式非法！',
          });
        } else if (res.scanType == "QR_CODE") {
          if (res.result.indexOf("http") >= 0) {
            that.setData({
              articleUrl: res.result,
              articleUrlNew: res.result
            });
          } else {
            wx.showModal({
              title: '提示',
              content: '链接格式非法！',
            });
          }
        }
      }
    })
  },

  articleUrlInput: function (e) {
    this.setData({
      articleUrlNew: e.detail.value
    })
  },

  doCatch: function () {
    var that = this;
    // 先尝试读取剪贴板中的链接
    wx.getClipboardData({
      success: function (clipRes) {
        var raw = (clipRes && clipRes.data) ? clipRes.data : '';
        var best = that.extractBestUrl(raw);
        if (best) {
          // 若剪贴板存在有效链接，直接填充并采集
          that.setData({
            articleUrl: best,
            articleUrlNew: best
          });
          that.performCatch(best);
        } else {
          // 否则回退到输入框中的链接
          that.catchFromInput();
        }
      },
      fail: function () {
        // 获取剪贴板失败则回退到输入框中的链接
        that.catchFromInput();
      }
    });
  },

  // 当剪贴板无有效链接时，从输入框执行采集
  catchFromInput: function () {
    var that = this;
    var articleUrlNew = (that.data.articleUrlNew || '').trim();
    if (articleUrlNew === '') {
      wx.showModal({
        title: '提示',
        content: '采集链接不能为空！'
      });
      return;
    }
    // 若输入不是以 http 开头，尝试在整段文本中提取最优 URL
    if (articleUrlNew.indexOf('http') !== 0) {
      var best = that.extractBestUrl(articleUrlNew);
      if (best) {
        that.setData({ articleUrl: best, articleUrlNew: best });
        that.performCatch(best);
        return;
      } else {
        wx.showModal({
          title: '提示',
          content: '未找到有效链接，请检查输入内容',
        });
        return;
      }
    }
    that.performCatch(articleUrlNew);
  },

  // 统一的采集执行方法
  performCatch: function (url) {
    var that = this;
    that.showLoading();
    var parameter = {};
    parameter['url'] = url;
    http.ApiGet(apiUrl.UrlDoCacth, parameter, function(res) {
      that.cancelLoading();
      var result = res.result;
      if (result && result.errorCode == 1) {
        that.setData({
          articleTitle: res.data.subject,
        });
        if (that.editorCtx && res.data.message) {
          that.editorCtx.setContents({
            html: res.data.message,
            success: (r) => { console.log(r); },
            fail: (e) => { console.log(e); }
          });
        }
        wx.showToast({
          title: '采集成功',
          icon: 'success',
          duration: 2000
        });
      } else {
        wx.showModal({
          title: '采集失败',
          content: (result && result.errorMessage) || '采集内容失败，请检查链接是否正确'
        });
      }
    });
  },
})